package com.collectplus.express.parcel;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.MainActivity;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.SerachStationBean;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.model.ServicePontListBean;
import com.collectplus.express.model.ServiceStateBean;
import com.collectplus.express.self.SelfBoxPictrueActivity;
import com.collectplus.express.self.SelfSerachStationAdapter;
import com.collectplus.express.self.SelfServicePointAdapter;
import com.collectplus.express.tools.TextWatcherExt;
import com.shouhuobao.bhi.loc.BaiduLocationService;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;

import droid.frame.umeng.UMeng;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.lang.JsonParser;

/**
 * 上门失败后可选择投递点重写了 SelfServicePointActivity.java
 * Created by lidandan on 2017/12/23.
 */

public class ParcelServicePointActivity extends BaseActivity2 implements View.OnClickListener {

    String serviceStation = "<strong><font color=#404040>服务点投递寄件</font></strong><font color=#4c4c4c><small><small> (不等待，下楼就能寄快递)</small></small></font>";
    String serviceStationNearby = "<font color=#4c4c4c>附近有</font><font color=#F7622E>{0}</font><font color=#4c4c4c>个驿站</font>";


    private ListView mListView;// 柜子列表
    private ListView mListView2;// 搜索结果列表

    private SelfServicePointAdapter mAdapter;

    // 选中按钮
    private CheckBox[] mGridRadio;
    /**
     * 箱格大中小微选取layout
     */
    private View mGridLayoutAlls;
    // 箱格父layout -- 小中大
    private ViewGroup[] mGridLayouts;
    /**
     * 四个查看大图imageview
     */
    private ImageView[] mEnlargeViews;
    private Button mSubmit;
    private HashMap<Integer, ServiceStateBean> cacheState = new HashMap<Integer, ServiceStateBean>();

    /**
     * 选择箱格提示
     */
    private LinearLayout mSelfChooseChest;

    private View mTitleLayout;// 顶部TitleLayout
    private EditText mSearchInput;// 搜索输入框
    private TextView mSearchOrCancel;// 搜索按钮(搜索状态显示取消)
    //    private PoiSearch mPoiSearch;
    /**
     * 只有点击搜索按钮才收起键盘 (通过联想不收起键盘)
     */
    private boolean autoSearch = true;

    private String currentCityName = "";
    private LinearLayout mVisitHomeLL;

    private String orderId;
    private String parcelId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        orderId = getIntent().getStringExtra("orderId");
        parcelId = getIntent().getStringExtra("parcelId");
        super.onCreate(savedInstanceState);
        refreshData();
    }


    @Override
    protected void findViewById() {
        setContentView(R.layout.self_service_point);
        super.findViewById();
        getAppTitle().setCommonTitle("选择投递方式");
        mTitleLayout = findViewById(R.id.app_title_layout);
        mListView = (ListView) findViewById(R.id.listview);
        mListView2 = (ListView) findViewById(R.id.listview2);
        mVisitHomeLL = (LinearLayout) findViewById(R.id.visit_home);
        mVisitHomeLL.setVisibility(View.GONE);
        ((TextView) findViewById(R.id.service_station_tv)).setText(Html.fromHtml(serviceStation));
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter == null || mAdapter.isEmpty()) {
                    return;
                }
                ServicePointBean clickItem = (ServicePointBean) parent.getItemAtPosition(position);
                int sid = clickItem.getId();
                mAdapter.setStation(clickItem.isStation());
                mAdapter.setSelected(clickItem);
                mAdapter.notifyDataSetChanged();
                // 驿站
                if (clickItem.isStation()) {
                    if (clickItem.isChecked()) { // 选中
                        setButtonEnableStyle(mSubmit, true);
                    } else {
                        setButtonEnableStyle(mSubmit, false);
                    }
                } else {
                    if (clickItem.isChecked()) {// 选中
                        UMeng.click(getContext(), "self_servicePoint_itemSelect_click");
                        ServiceStateBean cacheItem = cacheState.get(sid);
                        // 检查缓存 ==> 无
                        // if (cacheItem == null) {
                        // showLoadingDialog(null);
                        if (clickItem.getStatus() > 0) {
                            AppHttp.getInstance().cabinetGetState(clickItem.getCode());
                        } else {
                            ServiceStateBean stateBean = new ServiceStateBean();
                            stateBean.setBig(0);
                            stateBean.setMicro(0);
                            stateBean.setMiddle(0);
                            stateBean.setSmall(0);
                            updateGridLayout(stateBean);
                        }
                        // } else {
                        // 从缓存中读取
                        // updateGridLayout(cacheItem);
                        // }
                    } else {// 未选中
                        setButtonEnableStyle(mSubmit, false);
                        mGridLayoutAlls.setVisibility(View.GONE);
                        mSelfChooseChest.setVisibility(View.GONE);
                        for (int i = 0; i < mGridRadio.length; i++) {
                            // mGridRadio[i].setChecked(false);
                        }
                    }

                }
            }
        });
        // 大中小三个箱格layout
        mGridLayouts = new ViewGroup[4];
        mGridLayouts[0] = (ViewGroup) findViewById(R.id.box_micro);
        mGridLayouts[1] = (ViewGroup) findViewById(R.id.box_small);
        mGridLayouts[2] = (ViewGroup) findViewById(R.id.box_middle);
        mGridLayouts[3] = (ViewGroup) findViewById(R.id.box_big);
        for (int i = 0; i < mGridLayouts.length; i++) {
            mGridLayouts[i].setOnClickListener(this);

        }

        mEnlargeViews = new ImageView[4];
        mEnlargeViews[0] = (ImageView) findViewById(R.id.self_box_enlarge_image0);
        mEnlargeViews[1] = (ImageView) findViewById(R.id.self_box_enlarge_image1);
        mEnlargeViews[2] = (ImageView) findViewById(R.id.self_box_enlarge_image2);
        mEnlargeViews[3] = (ImageView) findViewById(R.id.self_box_enlarge_image3);
        for (int i = 0; i < mEnlargeViews.length; i++) {
            mEnlargeViews[i].setOnClickListener(this);

        }

        mGridRadio = new CheckBox[4];
        mGridRadio[0] = (CheckBox) findViewById(R.id.self_grid_select0);
        mGridRadio[1] = (CheckBox) findViewById(R.id.self_grid_select1);
        mGridRadio[2] = (CheckBox) findViewById(R.id.self_grid_select2);
        mGridRadio[3] = (CheckBox) findViewById(R.id.self_grid_select3);
        mGridLayoutAlls = findViewById(R.id.self_grid_layout);
        //
        mSubmit = (Button) findViewById(R.id.self_next_action);
        mSubmit.setText("确认选择");
        mSubmit.setOnClickListener(this);
        mSelfChooseChest = (LinearLayout) findViewById(R.id.self_choose_chest);
        setButtonEnableStyle(mSubmit, false);
        // 输入框
        mSearchInput = (EditText) findViewById(R.id.slef_search_edit);
        mSearchInput.clearFocus();
        mSearchInput.setFocusable(false);
        mSearchInput.setFocusableInTouchMode(false);
        mSearchInput.setOnClickListener(this);
        mSearchOrCancel = (TextView) findViewById(R.id.slef_search_submit);
        mSearchOrCancel.setOnClickListener(this);

        // mSearchInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
        mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchInput.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        String keywords = mSearchInput.getText().toString();
                        if (isEmpty(keywords)) {
                            // ignore
                        } else {
                            autoSearch = true;
                            if (isNotEmpty(currentCityName)) {
                                showLoadingDialog(null);
                                AppHttp.getInstance().serachNearStation(currentCityName, keywords);
                                //                                mPoiSearch.searchInCity((new PoiCitySearchOption()).city(currentCityName) //
                                //                                        .keyword(keywords).pageNum(1).pageCapacity(20));
                            }
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 1000);
            }
        });
        mSearchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keywords = mSearchInput.getText().toString();
                    if (isEmpty(keywords)) {
                        // ignore
                    } else {
                        autoSearch = false;
                        if (isNotEmpty(currentCityName)) {
                            showLoadingDialog(null);
                            AppHttp.getInstance().serachNearStation(currentCityName, keywords);
                            //                            mPoiSearch.searchInCity((new PoiCitySearchOption()).city(currentCityName) //
                            //                                    .keyword(keywords).pageNum(1).pageCapacity(20));
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void refreshData() {
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", MsgID.location_cabinet);
        startService(intent);
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 获取百度定位以后发请求 、查询附近柜子
            case MsgID.location_cabinet:
                BDLocation loc = (BDLocation) msg.obj;
                if (loc == null) {
                    cancelLoadingDialog();
                    showToast("定位失败");
                    return true;
                } else {
                    currentCityName = loc.getCity();
                    if (isNotEmpty(currentCityName)) {
                        showLoadingDialog("查询中");
                        AppHttp.getInstance().cabinetGetNearby2(loc.getLongitude(), loc.getLatitude());
                    } else {
                        cancelLoadingDialog();
                        showToast("定位失败");
                    }
                }
                return true;
            //根据关键字搜索附近驿站
            case MsgID.serach_station_for_keywords:
                cancelLoadingDialog();
                final SerachStationBean bean = JsonParser.parse(msg.obj + "", SerachStationBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bean != null && bean.getStatus() == 0) {
                            SelfSerachStationAdapter adapter = null;
                            if (bean.getResults() != null && bean.getResults().size() > 0) {
                                if (bean.getResults().size() == 1) {
                                    showToast("搜索结果为空");
                                    adapter = new SelfSerachStationAdapter(null, getContext());
                                    mListView2.setAdapter(adapter);
                                } else {
                                    adapter = new SelfSerachStationAdapter((ArrayList<SerachStationBean.ResultsBean>) bean.getResults(), getContext());
                                    mListView2.setAdapter(adapter);
                                    mListView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            SerachStationBean.ResultsBean item = (SerachStationBean.ResultsBean) parent.getItemAtPosition(position);
                                            if (item == null) {
                                                return;
                                            }
                                            showLoadingDialog("查询中");
                                            AppHttp.getInstance().cabinetGetNearby2(item.getLocation().getLng(), item.getLocation().getLat());
                                            // 切换视图
                                            onClick(mSearchOrCancel);
                                        }
                                    });
                                    if (autoSearch) {
                                        // 通过联想搜索 不收键盘
                                    } else {// 点击搜索 收起键盘
                                        getHandler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                ImmUtils.hide(getContext());
                                            }
                                        }, 200);
                                    }
                                }
                            } else {
                                adapter = new SelfSerachStationAdapter(null, getContext());
                                mListView2.setAdapter(adapter);
                                showToast("搜索结果为空");
                            }
                        } else {
                            showToast(bean.getMessage());
                        }
                    }
                });
                return false;
            // 查询附近柜子、驿站
            case MsgID.self_cabinet_nearby_alls:
                cancelLoadingDialog();
                final AppResult<ServicePontListBean> result = JSON.parser(msg.obj, ServicePontListBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            if (mListView.getAdapter() == null || mAdapter == null) {
                                mAdapter = new SelfServicePointAdapter(result.getResult().getList(), getContext());
                                if (result.getResult().getList() != null && result.getResult().getList().size() > 0) {
                                    mAdapter.setStation(result.getResult().getList().get(0).isStation());
                                    mAdapter.setSelected(result.getResult().getList().get(0));
                                }
                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.setItems(result.getResult().getList(), true);
                            }
                            ((TextView) findViewById(R.id.service_station_nearby_tv)).setText(Html.fromHtml(MessageFormat.format(serviceStationNearby, mAdapter.getItemsSize())));
                        } else {
                            ((TextView) findViewById(R.id.service_station_nearby_tv)).setText(Html.fromHtml(MessageFormat.format(serviceStationNearby, 0)));
                            mAdapter = new SelfServicePointAdapter(null, getContext());
                            mListView.setAdapter(mAdapter);
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            // 查询箱格状态、是否可用
            case MsgID.self_cabinet_usableState_get:
                cancelLoadingDialog();
                final AppResult<ServiceStateBean> result2 = JSON.parser(msg.obj, ServiceStateBean.class);
                if (result2.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ServiceStateBean stateBean = result2.getResult();
                            cacheState.put(msg.arg1, stateBean);
                            updateGridLayout(stateBean);
                        }
                    });
                } else {
                    showToast(result2.getMessage());
                }
                return true;
            case MsgID.query_parcel_send_way:
                cancelLoadingDialog();
                AppResult<?> result3 = JSON.parser(msg.obj);
                if (result3.isSuccess()) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    Bundle bundle = new Bundle();
                    bundle.putString("parcelId", parcelId);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                } else {
                    showToast(result3.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }

    }

    /**
     * 更新柜子状态
     *
     * @param item
     */
    private void updateGridLayout(ServiceStateBean item) {
        mGridLayoutAlls.setVisibility(View.VISIBLE);
        mSelfChooseChest.setVisibility(View.VISIBLE);
        findViewById(R.id.self_box_view).setVisibility(View.VISIBLE);
        // mGridLayoutAlls.setVisibility(View.VISIBLE);
        updateGridLayoutState(0, item.getMicro() > 0);
        updateGridLayoutState(1, item.getSmall() > 0);
        updateGridLayoutState(2, item.getMiddle() > 0);
        updateGridLayoutState(3, item.getBig() > 0);
    }

    /**
     * 更新箱格的状态(大中小是否可用)
     *
     * @param position 从0开始
     */
    private void updateGridLayoutState(int position, boolean usable) {
        ViewGroup viewGroup = mGridLayouts[position];
        ImageView pic = (ImageView) viewGroup.findViewById(getResources().getIdentifier("self_box_image" + position, "id", this.getPackageName()));
        pic.setEnabled(usable);
        // 长宽
        viewGroup.findViewById(getResources().getIdentifier("box_size_wide" + position, "id", this.getPackageName())).setEnabled(usable);
        // 高
        viewGroup.findViewById(getResources().getIdentifier("box_size_height" + position, "id", this.getPackageName())).setEnabled(usable);
        // 大小类型
        viewGroup.findViewById(getResources().getIdentifier("box_name" + position, "id", this.getPackageName())).setEnabled(usable);

        View check = viewGroup.findViewById(getResources().getIdentifier("self_grid_select" + position, "id", this.getPackageName()));
        check.setEnabled(usable);
        // 已满状态
        View status = viewGroup.findViewById(getResources().getIdentifier("box_status_hint" + position, "id", this.getPackageName()));
        status.setEnabled(usable);
        if (usable) {
            check.setVisibility(View.VISIBLE);
            status.setVisibility(View.GONE);
        } else {
            check.setVisibility(View.GONE);
            status.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < mGridLayouts[position].getChildCount(); i++) {
            // set onClick event
            mGridLayouts[position].setOnClickListener(usable ? ParcelServicePointActivity.this : null);
            //
            View child = mGridLayouts[position].getChildAt(i);
            if (child instanceof TextView) {
                int textColor = usable ? R.color.app_font_1 : R.color.app_font_2;
                TextView textView = ((TextView) child);
                textView.setTextColor(getResources().getColor(textColor));
                // 是否可用
                if (i == 1) {// 第2个child为是否可用
                    textView.setText(usable ? "可用" : "已满");
                }
            }
            // 可用状态
            if (child instanceof ImageView) {
                ImageView image = (ImageView) child;
                String name = "self_bag_state_" + (usable ? (position + 1) : (position + 1 + 3));
                int resId = getResources().getIdentifier(name, "drawable", getPackageName());
                image.setImageResource(resId);
            }
            // if (child instanceof CheckBox) {
            // CheckBox checkBox = ((CheckBox) child);
            // if (usable == false) {// 不可用
            // checkBox.setEnabled(false);
            // checkBox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.service_box_disable, 0, 0, 0);
            // } else {
            // checkBox.setEnabled(true);
            // checkBox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.app_checkbox_selector, 0, 0, 0);
            // }
            // }
        }
    }

    /**
     * 修改箱子的选中状态
     *
     * @param selected 选中箱子的位置
     */
    private void updateGridLayoutSelected(int selected) {
        // 还没选中
        if (mAdapter.getSelectedId() < 0) {
            showToast("请选择智能柜");
            return;
        }
        for (int i = 0; i < mGridRadio.length; i++) {
            if (i == selected) {
                mGridRadio[i].setChecked(true);
            } else {
                mGridRadio[i].setChecked(false);
            }
        }
        for (int i = 0; i < mEnlargeViews.length; i++) {
            if (i == selected) {
                mEnlargeViews[i].setVisibility(View.VISIBLE);
            } else {
                mEnlargeViews[i].setVisibility(View.GONE);
            }
        }
        setButtonEnableStyle(mSubmit, true);
    }

    private void startActivity2SelfEnlarge(int position) {
        Intent picIntent = new Intent(this, SelfBoxPictrueActivity.class);
        picIntent.putExtra("checkPosition", position);
        startActivity(picIntent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.self_box_enlarge_image0:
                startActivity2SelfEnlarge(0);
                break;
            case R.id.self_box_enlarge_image1:
                startActivity2SelfEnlarge(1);
                break;
            case R.id.self_box_enlarge_image2:
                startActivity2SelfEnlarge(2);
                break;
            case R.id.self_box_enlarge_image3:
                startActivity2SelfEnlarge(3);
                break;
            case R.id.box_micro:
                updateGridLayoutSelected(0);
                break;
            case R.id.box_small:
                updateGridLayoutSelected(1);
                break;
            case R.id.box_middle:
                updateGridLayoutSelected(2);
                break;
            case R.id.box_big:
                updateGridLayoutSelected(3);
                break;
            // 搜索框
            case R.id.slef_search_edit:
                // 非"搜索"状态下点击搜索框--切换到搜索状态
                if (mSearchOrCancel.getTag() == null) {
                    mSearchOrCancel.setVisibility(View.VISIBLE);
                    mSearchOrCancel.setTag("");//
                    mSearchOrCancel.setText("取消");
                    mTitleLayout.setVisibility(View.GONE);
                    mListView2.setVisibility(View.VISIBLE);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSearchInput.setFocusable(true);
                            mSearchInput.setFocusableInTouchMode(true);
                            mSearchInput.requestFocus();
                            ImmUtils.show(getContext(), mSearchInput);
                        }
                    }, 500);
                } else {
                    // 搜索状态点击, 不作处理
                }
                break;
            // 搜索
            case R.id.slef_search_submit:
                if (mSearchOrCancel.getTag() == null) {
                    // 非搜索状态, 点击搜索按钮不做处理
                } else {
                    // 取消
                    mSearchOrCancel.setTag(null);//
                    mSearchOrCancel.setText("搜索");
                    mSearchOrCancel.setVisibility(View.GONE);
                    mTitleLayout.setVisibility(View.VISIBLE);
                    mListView2.setVisibility(View.GONE);
                    mListView2.setAdapter(null);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSearchInput.setFocusable(false);
                            mSearchInput.setFocusableInTouchMode(false);
                            mSearchInput.clearFocus();
                            ImmUtils.hide(getContext());
                        }
                    }, 200);
                }
                break;
            // 预约智能柜
            case R.id.self_next_action:
                if (v.isEnabled() == false || mAdapter.getSelectedId() == -1) {
                    return;
                }
                ServicePointBean servicePoint = mAdapter.getSelectedItem(mAdapter.getSelectedId());
                if (servicePoint.isStation() == false) {
                    boolean isSelected = false;
                    int selectInt = 0;// 记录哪个箱格被选中
                    for (int i = mGridRadio.length - 1; i >= 0; i--) {
                        if (mGridRadio[i].isChecked()) {
                            selectInt = mGridRadio.length - i;
                        }
                        isSelected |= mGridRadio[i].isChecked();
                    }
                    if (isSelected == false) {
                        showToast("请选择智能柜和箱格尺寸");
                        return;
                    }
                    servicePoint.setSize(selectInt + "");
                }
                if (servicePoint.getType() == Const.ParcelType.bagToHome) {
                    AppHttp.getInstance().queryParcelSendWay(orderId, servicePoint.getId(), Const.ParcelType.bagToHome);
                } else {
                    AppHttp.getInstance().queryParcelSendWay(orderId, servicePoint.getId(), Const.ParcelType.bagToBox);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}


